package com.lovo.maotai.service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lovo.maotai.dao.IUserDao;
import com.lovo.maotai.entity.UserEntity;
import com.lovo.util.Verifier;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MTService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    IUserDao userDao;

    @RabbitListener(queues = "queueMT")
    public void  getGoodsOne(String token){
          //随机获取
        int randomInt = (int) (Math.random() * 2);
        if(randomInt==1){
           //查看库存是否存在,存在就通知用户，并持久化到数据库
            if(this.updateRepertory()){
                UserEntity u=new UserEntity();
                String json=Verifier.verifierJwt(token).getJson();
                JSONObject jsonObject=         JSONObject.parseObject(json);
                u.setUserName(jsonObject.getString("userName"));

                userDao.save(u);
                redisTemplate.opsForList().leftPush("mtResult",token);

            }

        }
    }

    @RabbitListener(queues = "queueMT")
    public void  getGoodsTwo(String token){
        //随机获取
        int randomInt = (int) (Math.random() * 2);
        if(randomInt==1){
            //查看库存是否存在,存在就通知用户，并持久化到数据库
            if(this.updateRepertory()){
                UserEntity u=new UserEntity();
                String json=Verifier.verifierJwt(token).getJson();
                JSONObject jsonObject=         JSONObject.parseObject(json);
                u.setUserName(jsonObject.getString("userName"));

                userDao.save(u);
                redisTemplate.opsForList().leftPush("mtResult",token);

            }

        }
    }

    public synchronized boolean  updateRepertory(){

    Object obj=    redisTemplate.opsForValue().get("mt");
   int num=   Integer.parseInt(String.valueOf(obj));

       if (num > 0) {
           num = num - 1;
           redisTemplate.opsForValue().set("mt", num);
           System.out.println("库存数"+num);
           return true;

   }
   return false;
    }
}
